package hk.cic.cwrs.bio.integration;



import org.json.JSONObject;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.util.Log;

import hk.cic.cwrs.bio.integration.log.IBioService;


public class cicInterfaceProxy {
	private final static String TAG="BioServiceProxy";
	private IBioService bioService ;
	
	private ServiceConnection bioConn ;
	private Context context;
	public static boolean isConnected=false;
	
	public cicInterfaceProxy(Context mContext){
		this.context=mContext;
		createCICInterfaceProxy();
	}
	
	private void createCICInterfaceProxy(){
		try{
			bioConn =  new ServiceConnection() {
				@Override
				public void onServiceDisconnected(ComponentName name) {
					// TODO Auto-generated method stub
					System.out.println("----------IBioService failure----------");
					isConnected=false;
				}
				@Override
				public void onServiceConnected(ComponentName name, IBinder service) {
					// TODO Auto-generated method stub
					bioService = IBioService.Stub.asInterface(service);
					isConnected=true;
					System.out.println("----------IBioService success----------");
				}
			};
			this.context.bindService(new Intent("hk.cic.cwrs.bio.integration.log.IBioService"), bioConn, Context.BIND_AUTO_CREATE);
		}catch(Exception ex){
			ex.printStackTrace();

		}
	}
	
	public boolean dispose(){
		if (bioConn != null) 
			this.context.unbindService(bioConn);
		isConnected=false;
		return true;
	}
	
	/**
	 * Callback cic resultlog service 
	 * @param result
	 * @return
	 */
	public boolean callbackCICResultLog(PinArchiveItem result){
		try {
			JSONObject json = new JSONObject();
		
			json.put("SessionID", result.SessionID);
			//CIClog.db中CWRNo 有可能去掉0 例如：CWR0125852 CWNo=125852
			//所以用 GreenCardExpire保存原始的CWRNo
			json.put("CWRNo", result.GreenCardExpire); 
			json.put("Result", SEGlobal.STATUS_SEND_WIEGAND_FAIL);
			json.put("Datetime", TimeUtil.format(System.currentTimeMillis(), TimeUtil.format1));
			
			if(bioService==null|| !isConnected) return false;
			
			bioService.ResultLog(json.toString());
			//CrashHandler.saveResultLog2File(this.context,TAG, "run", "[I] resultLog():josnString:"+json.toString());
			//Log.i(TAG, "====Last Request sendVerifyResult SessionID:"+result.SessionID+" CWRNo:"+result.CWRNo+" Result:"+result.Result+" Datetime:"+result.Datetime);
			return true;
		}catch(Exception ex){
			ex.printStackTrace();

			return false;
		}
	}
}
